<?php
declare (strict_types=1);

namespace app\common\logic;

use app\common\model\Order;
use app\common\model\OrderProduct;
use app\common\model\Product;
use app\common\model\User;

class StatisticsLogic{

    /**
     * 会员统计
     * @param $request
     * @return array
     */
    public function getUserData($request): array
    {
        try{
            $y = $request->param('year', date("Y"));
            $m = $request->param('month', date("Y-m"));

            $year = strtotime("+1 year", strtotime("{$y}-01-01"));
            $month = strtotime("+1 month", strtotime($m));

            $year_all = User::where('create_time', '<', $year)->count();
            $month_all = User::where('create_time', '<', $month)->count();

            $year_add = User::whereYear('create_time',$y)->count();
            $month_add = User::whereMonth('create_time',$m)->count();

            $year_rate = $year_all > 0 ? round($year_add/$year_all, 2) : 0;
            $month_rate = $month_all > 0 ? round($month_add/$month_all, 2) : 0;

            $data = [
                'year_all' => $year_all,
                'month_all' => $month_all,
                'year_add' => $year_add,
                'month_add' => $month_add,
                'year_rate' => $year_rate,
                'month_rate' => $month_rate,
            ];

            return ['code'=>1, 'msg'=>'success', 'data'=>$data];
        }catch (\Exception $e){
            return ['code'=>-1, 'msg'=>$e->getMessage()];
        }

    }

    /**
     * 业绩统计
     * @param $request
     * @return array
     */
    public function getConsumData($request): array
    {
        try{
            $y = $request->param('year', date("Y"));
            $m = $request->param('month', date("Y-m"));

            $year = strtotime("+1 year", strtotime("{$y}-01-01"));
            $month = strtotime("+1 month", strtotime($m));

            $year_all = Order::where('pay_time', '<', $year)->sum('real_amount');
            $month_all = Order::where('pay_time', '<', $month)->sum('real_amount');

            $year_add = Order::whereYear('pay_time',$y)->sum('real_amount');
            $month_add = Order::whereMonth('pay_time',$m)->sum('real_amount');

            $year_rate = $year_all > 0 ? round($year_add/$year_all, 2) : 0;
            $month_rate = $month_all > 0 ? round($month_add/$month_all, 2) : 0;

            $data = [
                'year_all' => $year_all,
                'month_all' => $month_all,
                'year_add' => $year_add,
                'month_add' => $month_add,
                'year_rate' => $year_rate,
                'month_rate' => $month_rate,
            ];

            return ['code'=>1, 'msg'=>'success', 'data'=>$data];
        }catch (\Exception $e){
            return ['code'=>-1, 'msg'=>$e->getMessage()];
        }

    }


}